/*
 * @Date: 2023-01-22 03:26:05
 * @LastEditors: 恶名扬 2080156129@qq.com
 * @LastEditTime: 2023-01-24 06:34:02
 * @FilePath: \campus-repair-platform\server\service\reception\repair.js
 */

/**
 * addRecordInfo    提交维修记录
 * updateRecordInfo 根据id修改维修记录
 * listRepair       获取报修单列表
 * addRepairInfo 提交报修申请
 * updateRepair     修改报修单信息
 * queryRepair      查询报修单
 * returnRepair     维修人员退单
 * receivingRepair  维修人员接单
 */

const repairTypeStatement = require("../../common/sql_sentences/repair_type")
const repairStatement = require("../../common/sql_sentences/repair")
const recordStatement = require("../../common/sql_sentences/maintenance_record")

exports.addRecordInfo = async (req, res) => {
  const data = req.body
  try {
    // 提交维修记录
    let sqlStr = recordStatement.insert({
      ...data,
      job_number: req.auth.job_number,
      id: ''
    })
    let results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("提交维修记录失败！", 10005)

    // 查找维修记录id
    sqlStr = recordStatement.select({
      job_number: req.auth.job_number
    })
    results = await RunSQL(sqlStr)
    console.log(results)
    if (!results.length) return res.successSend("提交维修记录成功，查找维修记录id失败！", 10005)

    // 往报修单添加维修记录id
    sqlStr = repairStatement.idUpdate(
      { m_id: results[0].id, state: 6 },
      data.id
    )
    results = await RunSQL(sqlStr)
    console.log(results)
    if (results.affectedRows !== 1) return res.successSend("提交维修记录成功，但往报修单添加维修记录id失败！", 10005)
    return res.successSend("提交维修记录成功！") // 修改成功
  } catch (error) {
    res.errSend(error)
  }
}

exports.updateRecordInfo = async (req, res) => {

  try {
    const data = req.body
    let sqlStr
    if (data.p_name || data.remark) sqlStr = recordStatement.idUpdate({ ...data, id: "" }, data.id)
    else sqlStr = 'update maintenance_record set p_name=null where id = uuid_to_bin("' + data.id + '")'
    let results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("修改维修记录失败！", 10005) // 执行语句成功，但影响函数不等于 1
    return res.successSend("修改维修记录成功！") // 修改成功
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}
// let sqlStr
// if (state) {
//   sqlStr = `and state and number = '*number'${type_id !== undefined ? ' and type_id = "' + type_id + '"' : ''}`

//   if (type === 1) {
//     sqlStr = sqlStr.replace('state', state === 7 ? 'state != 4' : '')
//     sqlStr = sqlStr.replace('number', 's_number')
//     sqlStr = sqlStr.replace('*number', s_number)
//   } else {
//     sqlStr = sqlStr.replace('state', 'state = ' + state + 'state != 6')
//     sqlStr = sqlStr.replace('number', 'r_number')
//     sqlStr = sqlStr.replace('*number', job_number)
//   }
// } else 
exports.listRepair = async (req, res) => {
  try {
    const { type_id, page, pagesize, state } = req.body
    const { type, s_number, job_number } = req.auth
    let query = { type_id, state }
    query = type == 1 ? { ...query, s_number } : { ...query, r_number: job_number }

    // 获取报修单总数
    let sqlStr = repairStatement.selectCount(query, type)
    let results = await RunSQL(sqlStr)
    total = results[0].total

    // 获取报修单列表
    sqlStr = repairStatement.selectLimit(query, page, pagesize, type)
    results = await RunSQL(sqlStr)
    return res.successSend("", 10000, { row: results, total })
  } catch (error) {
    res.errSend(error)
  }
}

exports.addRepairInfo = async (req, res) => {
  try {
    const data = req.body
    // 获取报修类型
    let sqlStr = repairTypeStatement.idSelect(data.type_id)
    let results = await RunSQL(sqlStr)
    if (!results.length) return res.successSend("没有找到报修类型！", 10005)

    // 添加报修信息
    const info = req.auth
    sqlStr = repairStatement.insert({
      ...data,
      s_number: info.s_number,
      s_name: info.name,
      type_name: results[0].name
    })
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("提交报修申请失败！", 10005)
    return res.successSend("提交报修申请成功！")
  } catch (error) {
    res.errSend(error)
  }
}

exports.updateRepair = async (req, res) => {
  const data = req.body
  try {
    // 查询报修单
    let sqlStr = repairStatement.idSelect(data.id)
    let results = await RunSQL(sqlStr)
    if (results[0].s_number !== req.auth.s_number) return res.successSend("操作失败！", 10005)
    sqlStr = repairStatement.idUpdate(
      { ...data },
      data.id, 1
    )
    // 操作数据库修改报修单信息
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1)
      return res.successSend("修改报修单信息失败！", 10005) // 执行语句成功，但影响函数不等于 1
    return res.successSend("修改报修单信息成功！") // 修改成功
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}

exports.getRepairInfo = async (req, res) => {
  try {
    // 查询报修单
    const sqlStr = repairStatement.idSelect(req.query.id)
    const results = await RunSQL(sqlStr)
    if (results.length !== 1) return res.successSend("没有查到报修单！", 10005) // 执行语句成功，但影响函数不等于 1
    if (req.auth.r_number ? results[0].r_number !== req.auth.r_number : results[0].s_number !== req.auth.s_number) return res.successSend("没有权限查看！", 10005)
    return res.successSend("查询报修单成功！", 10000, results[0])
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}
// let sqlStr
// if (state) {
//   sqlStr = ` and state and id = uuid_to_bin('${id}') and number = '*number')`
//   if (type === 1) {
//     sqlStr = sqlStr.replace('state', state === 7 ? 'state != 4' : '')
//     sqlStr = sqlStr.replace('*number', s_number)
//     sqlStr = sqlStr.replace('state', 'state != 4')
//   } else {
//     sqlStr = sqlStr.replace('number', 'r_number')
//     sqlStr = sqlStr.replace('*number', job_number)
//     sqlStr = sqlStr.replace('state', 'state = ' + state + 'state != 6')
//   }
// } else 
exports.queryRepair = async (req, res) => {
  try {
    const { id, state } = req.body
    const { type, s_number, job_number } = req.auth
    let query = { id, state }
    query = type == 1 ? { ...query, s_number } : { ...query, r_number: job_number }

    // 查询报修单
    const sqlStr = repairStatement.select(query, type)
    const results = await RunSQL(sqlStr)
    if (results.length !== 1) return res.successSend("没有查到报修单！", 10005) // 执行语句成功，但影响函数不等于 1
    return res.successSend("查询报修单成功！", 10000, results[0])
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}

exports.returnRepair = async (req, res) => {
  const data = req.body
  const job_number = req.auth.job_number

  // 查找报修单
  let sqlStr = repairStatement.idSelect(data.id)
  let results = await RunSQL(sqlStr)
  if (results.length !== 1) return res.successSend("报修单不存在！", 10005)
  let result = results[0]
  // 执行语句成功，但该报修单不属于该维修人员
  if (result.r_number !== job_number) return res.successSend("操作失败，没有权限！", 10005)
  if (!(result.state === 4 || (data.isReturn && result.state === 5))) return res.errSend('报修单状态错误！')

  try {
    // 退单
    if (data.isReturn) sqlStr = repairStatement.idUpdate({ state: 2, r_number: '' }, data.id)
    // 接单
    else sqlStr = repairStatement.idUpdate({ state: 5, cause: data.cause }, data.id)
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("操作失败！", 10005)
    return res.successSend("操作成功！", 10000)
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}

exports.affirmRepair = async (req, res) => {
  const data = req.body
  const s_number = req.auth.s_number

  // 查找报修单
  let sqlStr = repairStatement.idSelect(data.id)
  let results = await RunSQL(sqlStr)
  if (results.length !== 1) return res.successSend("报修单不存在！", 10005)
  let result = results[0]
  // 执行语句成功，但该报修单不属于该学生
  if (result.s_number !== s_number) return res.successSend("操作失败，没有权限！", 10005)
  if (!(result.state === 6 || (data.isAffirm && result.state === 7))) return res.errSend('报修单状态错误！')

  try {
    // 完成
    if (data.isAffirm) sqlStr = repairStatement.idUpdate({ state: 8 }, data.id)
    // 未完成
    else sqlStr = repairStatement.idUpdate({ state: 7, cause: data.cause }, data.id)
    console.log(sqlStr)
    results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1) return res.successSend("操作失败！", 10005)
    return res.successSend("操作成功！", 10000)
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}